/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package avl.sv.server.slides;

import avl.sv.server.PropertiesManager;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author benbryan
 */
public class UploadAuthManager {
    private static UploadAuthManager instance = null;
    private final static HashMap<String,UploadAuth> uploadAuths = new HashMap<>();

    public UploadAuth getAuth(String key) {
        return uploadAuths.get(key);
    }

    public UploadAuth putAuth(String key, UploadAuth value) {
        return uploadAuths.put(key, value);
    }
    
    public UploadAuth removeAuth(String key){
        return uploadAuths.remove(key);
    }
    
    private UploadAuthManager() { 
        TimerTask purgeUserTask = new TimerTask() {
            @Override
            public void run() {
                try {
                purgeExpiredAuths();
                } catch (Exception ex){
                    Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Failure while purging expired auths", ex);
                }
            }
        };
        Timer purgeUserTimer = new Timer();
        int timeout = 1000*60/10*PropertiesManager.getUploadTimeoutMinutes();
        purgeUserTimer.schedule(purgeUserTask, timeout, timeout);
    }
    
    private void purgeExpiredAuths(){
        for (String key:uploadAuths.keySet()){
            UploadAuth auth = uploadAuths.get(key);
            if (auth.isExpired()){
                uploadAuths.remove(key);
                new Slides().deleteSlide(auth.slideSetName, auth.fileName);
            }
        }        
    }
    
    public static UploadAuthManager getInstance(){
        if(instance == null){
            instance = new UploadAuthManager();
        }
        return instance;
    }
    
}
